package csc.fresher.finalgroupfour.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import csc.fresher.finalgroupfour.domain.User;
import csc.fresher.finalgroupfour.service.BankService;

public class AuthentificationFailureListener implements
		AuthenticationFailureHandler {

	@Autowired
	private BankService bankService;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException ae)
			throws IOException, ServletException {
		// UsernamePasswordAuthenticationToken user =
		// (UsernamePasswordAuthenticationToken)
		// SecurityContextHolder.getContext().getAuthentication();
		HttpSession session = request.getSession();
		String loginId = request.getParameter("loginId");
		User userLock = bankService.findUser(loginId);
		if (userLock == null) {
			session.setAttribute("errorMessage", "Your Account does not exist");
			response.sendRedirect("login?error=true");
		} else {
			userLock.setCount(userLock.getCount() + 1);
			bankService.updateUser(userLock);
			session.setAttribute("errorMessage", "Invalid username or password");
			// user contains required data

			if (userLock.getCount() >= 3
					|| userLock.getUserState().equalsIgnoreCase("disable")) {
				userLock.setUserState("disable");
				session.setAttribute("errorMessage",
						"Your Account has been locked");
				userLock.setCount(0);
				bankService.updateUser(userLock);
			}
			response.sendRedirect("login?error=true");
		}

	}
}